using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace GushiJGg.ViewModels
{
    public class ReadDataViewModel
    {
        private string dir;
        Random wordRandom=new Random();
        public void Init(string dir)
        {
            this.dir = dir;
            getRandFileTxt();
        }

        private void getRandFileTxt()
        {
            var rand = new Random();
            var files = new DirectoryInfo(dir).GetFiles();
            var index = rand.Next() % files.Length;
            var path = files[index].FullName;
//            this.Path = path;
            var txt = System.IO.File.ReadAllText(path);
            var lines = txt.Split("，。".ToCharArray()).Select(m=>m.Trim()).Where(m=>!string.IsNullOrWhiteSpace(m)).ToList();
            index = rand.Next() % lines.Count();
            this.Line = lines[index].Trim();
            foreach (var word in this.Line.ToCharArray())
            {
                this.AddWord(word.ToString());
            }

            this.AddOtherWord(lines.Where(m => m != this.Line));
            this.RandWord = words.OrderBy(m => m.Rand).Select(m => m.Word).ToList();

        }

        public List<string> RandWord { get; set; }

        private void AddOtherWord(IEnumerable<string> strs)
        {
            var txt = string.Join("", strs);
            var rand = new Random();
            while (words.Count<9)
            {
                var index = rand.Next() % txt.Length;
                var word = txt.ToCharArray()[index].ToString();
                AddWord(word);
            }
        }

        private void AddWord(string word)
        {
            var it = new WordRand()
            {
                Word = word,
                Rand = wordRandom.Next()
            };
            words.Add(it);

        }


        public string Path { get; set; }
        List<WordRand> words=new List<WordRand>();

        public string Line { get; set; }
        public class WordRand
        {
            public string Word { get; set; }
            public int Rand { get; set; }
        }
    }
}